package org.slg.oracleproject.config;

import org.slg.oracleproject.exception.BusinessException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import jakarta.servlet.http.HttpServletResponse;

import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
public class GlobalExceptionHandler {

    // 处理认证失败异常（如Token无效、未登录）
    @ExceptionHandler(AuthenticationException.class)
    public Map<String, String> handleAuthenticationException(AuthenticationException e, HttpServletResponse response) {
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 401状态码
        Map<String, String> result = new HashMap<>();
        result.put("data", "null");
        result.put("msg", "认证失败：" + e.getMessage());
        result.put("code", "401");
        return result;
    }

    // 处理权限不足异常
    @ExceptionHandler(AccessDeniedException.class)
    public Map<String, String> handleAccessDeniedException(AccessDeniedException e, HttpServletResponse response) {
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_FORBIDDEN); // 403状态码
        Map<String, String> result = new HashMap<>();
        result.put("data", "null");
        result.put("msg", "权限不足：" + e.getMessage());
        result.put("code", "403");
        return result;
    }

    // 处理业务异常
    @ExceptionHandler(BusinessException.class)
    public Map<String, String> handleBusinessException(BusinessException e, HttpServletResponse response) {
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); // 500状态码
        Map<String, String> result = new HashMap<>();
        result.put("data", "null");
        result.put("msg", e.getMessage());
        result.put("code", "500");
        return result;
    }
}